import util from '../util.js';
import pool from './db.js';

// 查询所有音乐
export async function getAllUser() {
    const [rows] = await pool.query('SELECT * FROM user');
    return rows;
}

// 根据ID查询用户
export async function getUserById(id) {
    const [rows] = await pool.query('SELECT * FROM user WHERE id = ?', [id]);
    return rows[0];
}

// 添加用户
export async function addUser(user) {
    const { name, pass, times } = user;
    const now = util.getDatetime();
    const [result] = await pool.query(
        'INSERT INTO user (name, pass, create_time, update_time, times) VALUES (?, ?, ?, ?, ?)',
        [name, pass, now, now, times || 0]
    );
    return result.insertId;
}

// 更新用户
export async function updateUser(id, user) {
    const fields = [];
    const values = [];

    if (user.name !== undefined) {
        fields.push('name = ?');
        values.push(user.name);
    }
    if (user.pass !== undefined) {
        fields.push('pass = ?');
        values.push(user.pass);
    }
    if (user.times !== undefined) {
        fields.push('times = ?');
        values.push(user.times);
    }
    fields.push('update_time = ?');
    values.push(util.getDatetime());

    values.push(id);

    const sql = `UPDATE user SET ${fields.join(', ')} WHERE id = ?`;
    const [result] = await pool.query(sql, values);
    return result.affectedRows > 0;
}

// 删除用户
export async function deleteUser(id) {
    const [result] = await pool.query('DELETE FROM user WHERE id = ?', [id]);
    return result.affectedRows > 0;
}

// 登录
export async function login(name, pass) {
    const [rows] = await pool.query('SELECT * FROM user WHERE name = ? AND pass = ?', [name, pass]);
    return rows[0];
}